package com.tledu.jdbc;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;

/**
 * 1. 防止sql注入
 * 2. 提高开发效率，不需要在去拼接字符串了，也让我们代码更加简洁了
 *
 */
public class Jdbc2 {
    public static void main(String[] args) throws ClassNotFoundException {
        Class.forName("com.mysql.cj.jdbc.Driver");
        try {
            Connection connection = DriverManager.getConnection(
                    "jdbc:mysql://127.0.0.1:3306/jingmao19?serverTimezone=UTC&useUnicode=true&characterEncoding=UTF-8",
                    "root",
                    "root"
            );
            // 定义sql
            String sql = "insert into stu (name,age) value (?,?)";
            // 获取预编译的sql
            PreparedStatement preparedStatement = connection.prepareStatement(sql);
            // 添加参数
            preparedStatement.setString(1,"预编译sql");
            preparedStatement.setInt(2, 25);
            // 执行sql
            preparedStatement.execute();
            // 关闭连接
            preparedStatement.close();
            connection.close();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
    }
}
